package com.daipresents.gfmon;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;

import org.apache.log4j.Logger;

public class MemoryMonitor implements MemoryMonitorMBean {

    private static final String SUCCESS = "success";
    
    private Logger logger = Logger.getLogger(MemoryMonitor.class);
    private MemoryMXBean bean;
    
    public MemoryMonitor() {
        super();
        logger.debug(MemoryMonitor.class.getName() + "Constractor Called.");
        
        bean = (MemoryMXBean) ManagementFactory.getMemoryMXBean();
    }
    
    @Override
    public String getLogging(){
        String message = 
            String.format("HeapMemoryUsage:%s,NonHeapMemoryUsage:%s",
                    getHeapMemoryUsageInPercent(),
                    getNonHeapMemoryUsageInPercent());
        logger.info(message);
        return SUCCESS;
    }
    
    @Override
    public int getHeapMemoryUsageInPercent() {
        return getMemoryUsageInPercent(bean.getHeapMemoryUsage());
    }

    @Override
    public int getNonHeapMemoryUsageInPercent() {
        return getMemoryUsageInPercent(bean.getNonHeapMemoryUsage());
    }

    private int getMemoryUsageInPercent(MemoryUsage usage){
        if(usage == null){
            return 0;
        }
        
        long used = usage.getUsed();
        long max = usage.getMax();
        
        return (int) (100 * used / max);
    }
}
